package u.can.i.up.db;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MsSession {

	public volatile static MsSession instance;

	private SqlSession sqlSession;

	private Reader reader;

	public MsSession() {
	}

	public static MsSession getInstance() {
		if (instance == null) {
			instance = new MsSession();
		}
		return instance;
	}

	public SqlSession getSqlSession() {
		if (sqlSession == null) {
			sqlSession = sessionInit();
		}
		return sqlSession;
	}

	private SqlSession sessionInit() {
		try {
			reader = Resources.getResourceAsReader("MybatisConfig.xml");
			SqlSessionFactoryBuilder ssfBuilder = new SqlSessionFactoryBuilder();
			SqlSessionFactory sqlSessionFactory = ssfBuilder.build(reader, "mysql");
			sqlSession = sqlSessionFactory.openSession();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sqlSession;
	}

	public void sessionClose() {
		try {
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
